<?php


require_once('library.php');
//require_once('recaptcha/recaptchalib.php');

/**
 * ReCaptcha checking
 * @param string $privatekey
 * @param string $challange
 * @param string $response
 */
function amber_captcha_check($privatekey, $challange, $response) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER['REMOTE_ADDR'],
                                        $challange,
                                        $response);
        return $resp->is_valid;
}

/**
 * Custom encryption
 * @param string $str
 * @param string $key
 */
function amber_encrypt_string($str, $key) {
    return encrypt_string('AMBER'.$str, $key);
}

/**
 * Custom decryption
 * @param string $str
 * @param string $key
 */
function amber_decrypt_string($str, $key) {
    $str = decrypt_string($str, $key);
    if ('AMBER' == substr($str, 0, 5)) {
        return substr($str, 5);
    }
    return FALSE;
}


/**
 * Generate random nickname
 */
function amber_gen_nickname() {
    return 'anonymous user #' . mt_rand();
}

/**
 * Hash password
 * @param string $pswd
 */
function amber_hash_password($pswd) {
    return md5(md5($pswd)+$pswd+AMBER_PSWD_SALT);
}

/**
 * Send back error and stop execution
 * @param array $error    - array data
 */
function amber_send_error($message) {
    echo json_encode(array('err' => $message));
    die();
}

function amber_send_notice($code, $info) {
    echo json_encode(array(
        'notice' => $code,
        'info' => $info,
    ));

    die();
}

function amber_send_data($data) {
    echo json_encode(array(
        'resp' => $data
    ));
    exit(0);
}

function init_db($dsn, $user, $password, $options) {
    try {
        $GLOBALS['#dbh'] = new PDO($dsn, $user, $password, $options);

        /**
         * Sugar to get access to database object
         * @return PDO
         */
        function xdbh() {
            return $GLOBALS['#dbh'];
        }

    } catch (PDOException $e) {
        amber_send_error('dberror', 'Connection failed: ' . $e->getMessage());
    }
}


function amber_sk_hash($sk) {
    return md5(md5($sk));
}

function amber_run_query($sql, $args, $dieonerr=TRUE) {
    $sth = xdbh()->prepare($sql);

    if (!$sth->execute($args)) {
        if ($dieonerr) {
            if (xdbg()->can_debug()) {
                var_dump($sth->errorInfo());
            } else {
                amber_send_error('Oops. Something goes wrong with database. Please try again later.' );
            }
        } else {
            return $sth->errorCode();
        }
    }

    return  $sth->fetchAll(PDO::FETCH_ASSOC);
    ;
}



function amber_get_children($id) {
    $sql = "
    SELECT `id`, `parent_id`, `message`, `nickname`,
           UNIX_TIMESTAMP(`created`) AS `created`,
           UNIX_TIMESTAMP(`expire`) AS `expire`,
           EXISTS (
                   SELECT *
                     FROM `amber_messages` AS `msg_inner`
                    WHERE `msg_inner`.`parent_id` = `msg_outer`.`id`
                      AND `expire` > NOW()
                  ) AS `nested`
      FROM `amber_messages` as `msg_outer`
     WHERE `parent_id` = :id
       AND `expire` > NOW()
  ORDER BY `created`, `id`
    ";

    return amber_run_query($sql, array(':id' => $id));
}

?>
